require('es6-promise').polyfill()
// import axios from 'axios'
import qs from 'qs'
// import {debounce} from 'vux'
// import Vue from 'vue'
import { ISLOADING } from 'store/user'
import {bsApi} from './config-api'
axios.interceptors.request.use(config => {
   if(!global.myLoad){
       Vue.$vux.loading.show({
           text: '加载中...',
       })
   }
    return config
}, error => {
    return Promise.reject(error)
})


axios.interceptors.response.use(response => {

    return response
}, error => {
    console.log(typeof error)
    //  处理超时
    var str = error + ''
    if (str.search('timeout') !== -1) {   // 超时error捕获
        console.log('哈哈，你又超时了')
    }
    return Promise.resolve(error.response)
})

function errorState(response) {
    Vue.$vux.loading.hide()
    // 如果http状态码正常，则直接返回数据
    if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        /*AlertModule.show({
            title: '提示',
            content: response.data.describe||'网络异常',
            onShow () {
            },
            onHide () {
            }
        })*/
        if(response.data.code == 'C001B009'){
          Vue.$vux.toast.text(response.data.describe||'网络异常', 'middle')
            Vue.prototype.Interactive.loginOut();
        } else {
          Vue.$vux.toast.text(response.data.describe||'网络异常', 'middle')
        }
        // Vue.$vux.toast.text(response.data.describe||'网络异常', 'middle')
        return response.data
        // 如果不需要除了data之外的数据，可以直接 return response.data
    }else{
        /*AlertModule.show({
            title: '提示',
            content: '网络异常',
            onShow () {
            },
            onHide () {
            }
        })*/
        Vue.$vux.toast.text('网络异常', 'middle')

    }

}

function successState(res) {
    Vue.$vux.loading.hide();
    //统一判断后端返回的错误码
    if(res.data.errCode == '00000000'){
        /*AlertModule.show({
            title: '提示',
            content: res.data.describe||'网络异常',
            onShow () {
            },
            onHide () {
            }
        })*/
        Vue.$vux.toast.text(res.data.describe||'网络异常', 'middle')
    }else if(res.data.errCode != '00000000') {
        /*AlertModule.show({
            title: '提示',
            content: res.data.describe||'网络异常',
            onShow () {
            },
            onHide () {
            }
        })*/
        Vue.$vux.toast.text(res.data.describe||'网络异常', 'middle')
    }
}

const httpServer = (opts, data) => {
    // addPromise(httpServer)
    let token =Vue.prototype.comJS.getCookie('t');
    let Public = { //公共参数
        'loginToken': token
    }
    let httpDefaultOpts = { //http默认配置
        method:opts.method,
        // baseURL:'https://api.shbs008.com',
        // baseURL:'https://dev-api.shbs008.com',
        // baseURL:'https://test-api.shbs008.com',
        // baseURL:'https://stage-api.shbs008.com',
        baseURL: bsApi,
      url: opts.url,
        timeout: 30000,
        params:Object.assign(Public, data),
        data: opts.dataIsJson?Object.assign(Public, data):qs.stringify(Object.assign(Public, data)),
        headers: opts.method=='get'?{
            'X-Requested-With': 'XMLHttpRequest',
            "Accept": "application/json",
            "Content-Type": "application/json; charset=UTF-8"
        }:{
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }
    if(opts.method=='get'){
        httpDefaultOpts.headers = {
            'X-Requested-With': 'XMLHttpRequest',
            "Accept": "application/json",
            "Content-Type": "application/json; charset=UTF-8"
        }
        delete httpDefaultOpts.data
    }else if(opts.dataIsJson &&opts.method=='post'){
        httpDefaultOpts.headers = {
            'X-Requested-With': 'XMLHttpRequest',
            "Accept": "application/json",
            "Content-Type": "application/json; charset=UTF-8"
        }
        delete httpDefaultOpts.params
    } else {
        httpDefaultOpts.headers = {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        delete httpDefaultOpts.params
    }
    let promise = new Promise(function(resolve, reject) {
        axios(httpDefaultOpts).then(
            (res) => {
                global.myLoad = false
                Vue.$vux.loading.hide()
                // successState(res)
                if(res.data.code == "00000000"){
                    resolve(res.data)
                }else{
                  if(res.data.info && res.data.info == 'OK'){
                    reject(res);
                  }else{
                    global.myLoad = false
                    errorState(res);
                    reject(res);
                  }
                }

            }
        ).catch(
            (response) => {
                global.myLoad = false
                errorState(response)
                reject(response)
            }
        )

    })
    return promise
}
var arr = []
function addPromise(data) {
    var timer = null
    arr.push(data)
    timer = setTimeout(function () {
        Promise.all(arr)
            .then(res => {
                clearTimeout(timer)
                Vue.$vux.loading.hide()
                console.log(res, 'addPromise')
                arr = []
            })
    }, 100)
}

let post = (url, data) => {
    // console.log(data, '去空')
    return httpServer({url: url, method: 'post'}, data)
}

let postJson = (url, data) => {
    return httpServer({url: url, method: 'post',dataIsJson : true}, data)
}

let get = (url, data) => {
    return httpServer({url: url, method: 'get'}, data)
}


export {post, get, postJson}
// export default httpServer
